import React from "react";

import PageContent from '../PageContent'

import {Row,Col,Alert} from 'antd';

import { ajax ,showResultMessage} from '../common';

import {UIDataTableView,UIDataTreeView} from '../uicomponents/UIDataComponentView';
import UIFormView from '../uicomponents/UIFormView';
import UIForm from '../uicomponents/UIForm';
import UICardTabs from '../uicomponents/UICardTabs';

/** 
 * 系统组织部门列表
*/
class SysDepartmentListPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    refreshData = () => {
        this.departmentListRef.loadData();
    }

    actionHandler = (actionEvent) => {
        
        const { addNewSysDepartmentRef, departmentListRef, selectSysDepIds } = this;
        return {
            addNewDep: () => {
                addNewSysDepartmentRef.openModal();
            },
            closeDialog: () => {
                addNewSysDepartmentRef.closeModal();
            },
            refresh: () => {
                departmentListRef.loadData();
            },
            doOk: () => {
                const result = {};
                addNewSysDepartmentRef.getFormData(formData => {
                    if (formData.parentId == null) {
                        formData.parentId = 0;
                    }
                    ajax('SYSTEM/SYSDEP/saveDep', formData).then((data) => {
                        if (data) {
                            result.success = true;
                            result.message = 'message.saveSuccess';
                            addNewSysDepartmentRef.closeModal();
                            departmentListRef.loadData();
                        }
                    }).catch(function (reason) {
                        result.success = false;
                        result.message = reason;
                    }).finally(() => {
                        showResultMessage(result);
                    });
                });
            },
            deleteSysDep: () => {
                const result = {};
                ajax('SYSTEM/SYSDEP/deleteSysDep', { id: selectSysDepIds }).then((data) => {
                    if (data) {
                        result.success = true;
                        result.message = 'message.deleteSuccess';
                        departmentListRef.loadData();
                        if (this.props.onDepartmentSelected) {
                            this.props.onDepartmentSelected(null);
                        }
                    }
                }).catch(function (reason) {
                    result.success = false;
                    result.message = reason;
                }).finally(() => {
                    showResultMessage(result);
                });

            }
        };
    }

    render() {
        return (
            <React.Fragment>
                <UIDataTreeView
                    title="组织部门列表"
                    actionGroupId="sysDepartmentActionGroup"
                    dataUrl="SYSTEM/sysDepartmentTree/buildTree"
                    expandLevel={-1}
                    ref={(inst) => this.departmentListRef = inst}
                    actionHandler={this.actionHandler}
                    onSelectChange={(selectRowKeys, node) => {
                        this.selectSysDepIds = node !== undefined ? [node.props.dataRef.nodeData.id] : [];
                        if (this.props.onDepartmentSelected && node != null) {
                            this.props.onDepartmentSelected(node.props.dataRef.nodeData);
                        }
                    }}
                    setToolbarState={(topToolBar, selectSysDepIds) => {
                        if (selectSysDepIds != null && selectSysDepIds.length > 0) {
                            topToolBar.enable('delete');
                            topToolBar.enable('edit');
                        }
                        else {
                            topToolBar.disable('delete');
                            topToolBar.disable('edit');
                        }
                    }}
                />
                <UIFormView
                    title="新建系统组织部门"
                    inPop={true}
                    formConfigId="sysDepartmentForm"
                    actionGroupId="defaultDiaoligActionGroup"
                    ref={(inst) => this.addNewSysDepartmentRef = inst}
                    destroyOnClose={true}
                    actionHandler={this.actionHandler}
                >
                </UIFormView>
            </React.Fragment>
        );
    }
}

/**
 * 系统组织部门编辑表单
 */
class SysDepartmentEditPanel extends React.Component {
    constructor(props) {
        super(props);

    }

    setDepartment = (department) => {
        this.formRef.setFormData(department);
    }

    actionHandler = (actionEvent) => {
        const owner = this;
        return {
            doSave: () => {
                actionEvent.component.getFormData((formData) => {
                    const result = {};
                    ajax('SYSTEM/SYSDEP/saveDep', formData).then((data) => {
                        if (data) {
                            result.success = true;
                            result.message = 'message.saveSuccess';
                            if (owner.props.onSaveSysDep) {
                                owner.props.onSaveSysDep(data);
                            }
                        }
                    }).catch(function (reason) {
                        result.success = false;
                        result.message = reason;
                    }).finally(() => {
                        //console.log(result);
                        showResultMessage(result);
                    });
                });
            }
        };
    }

    render() {
        return (
            <UIForm
                formConfigId="sysDepartmentEditForm"
                actionGroupId="saveActionGroup"
                wrappedComponentRef={(inst) => this.formRef = inst}
                actionHandler={this.actionHandler}
            />
        );
    }
}

/**
 * 系统组织部门成员列表
 */
class SysDepartmentStaffListPanel extends React.Component {

    constructor(props) {
        super(props);
    }

    setDepartment = (department) => {
        this.department = department;
        this.tableRef.loadData({ id: department.id });
    }

    actionHandler = (actionEvent) => {
        const { department, selectDepUserIds } = this;
        return {
            addNewDepUser: () => {
                this.querySysUserRef.openModal(() => {
                    this.querySysUserRef.loadData({ depId: department.id });
                });
            },
            deleteSysDepUser: () => {
                ajax("SYSTEM/SYSDEP/deleteSysDepUser", { ids: selectDepUserIds }, (data) => {
                    this.tableRef.loadData({ id: department.id });
                });
            },
            setDepManager: () => {
                ajax("SYSTEM/SYSDEP/setDepUserRoles", { depId: department.id, ids: selectDepUserIds, role: 'manager' }, (data) => {
                    this.tableRef.loadData({ id: department.id });
                });
            },
            setDepStaff: () => {
                ajax("SYSTEM/SYSDEP/setDepUserRoles", { depId: department.id, ids: selectDepUserIds, role: 'member' }, (data) => {
                    this.tableRef.loadData({ id: department.id });
                });
            },
            cancelChooseSysUser: () => {
                this.querySysUserRef.closeModal();
            },
            addRelatedSysUsers: () => {
                const { selectSysUserIds } = this;
                ajax("SYSTEM/SYSDEP/addDepUsers", { depId: department.id, userIds: selectSysUserIds }, () => {
                    this.querySysUserRef.closeModal();
                    this.tableRef.loadData({ id: department.id });
                });
            }
        };
    }

    render() {

        const dataTableProps = {
            actionGroupId: "sysDepUserActionGroup",
            tableConfigId: "systemDepUserList",
            dataUrl: "SYSTEM/SYSDEP/querySysDepRelatedUserList",
            selectMode: "multi",
            autoLoad: false,
            bordered: false,
            setToolbarState: (topToolBar, selectDepUserIds) => {
                if (selectDepUserIds != null && selectDepUserIds.length > 0) {
                    topToolBar.enable('delete');
                    topToolBar.enable('setDepUserRole');
                }
                else {
                    topToolBar.disable('delete');
                    topToolBar.disable('setDepUserRole');
                }
            },
            actionHandler: this.actionHandler,
            onSelectChange: (selectRowKeys) => {
                this.selectDepUserIds = selectRowKeys;
            }

        };

        const querySysUserDataTableProps = {
            title: "选择部门成员",
            width: 800,
            destroyOnClose: true,
            actionGroupId: "chooseSysUserListActionGroup",
            tableConfigId: "systemUserList",
            dataUrl: "SYSTEM/SYSDEP/querySysUserNotInDepList",
            selectMode: "multi",
            searchFormId: "sysUserQueryForm",
            autoLoad: false,
            bordered: false,
            inPop: true,
            
            setToolbarState: (topToolBar, selectSysUserIds) => {
                if (selectSysUserIds != null && selectSysUserIds.length > 0) {
                    topToolBar.enable('ok');
                }
                else {
                    topToolBar.disable('ok');
                }
            },
            actionHandler: this.actionHandler,
            onSelectChange: (selectRowKeys) => {
                this.selectSysUserIds = selectRowKeys;
            }

        }

        return (
            <React.Fragment>
                <UIDataTableView key="DepStaffList" {...dataTableProps} ref={(inst) => this.tableRef = inst} />
                <UIDataTableView key="QuerySysUser" {...querySysUserDataTableProps} ref={(inst) => this.querySysUserRef = inst} />
            </React.Fragment>
        );
    }
}

/** 
 * 系统组织部门信息
*/
class SysDepartmentInfoPanel extends React.Component {

    constructor(props) {
        super(props);

    }

    setDepartment = (department) => {
        this.department = department;
        if (this.sysDepEditFormRef != null) {
            this.sysDepEditFormRef.setDepartment(department);
        }
        if (this.sysDepStaffListRef != null) {
            this.sysDepStaffListRef.setDepartment(department);
        }
    }

    onTabChange = (tabName) => {
        switch (tabName) {
            case 'sysDepartmentEditorPart':
                this.sysDepEditFormRef.setDepartment(this.department);
                break;
            case 'sysDepartmentStaffList':
                this.sysDepStaffListRef.setDepartment(this.department);
                break;
        }
    }

    render() {

        const tabPanelContentMap = {
            '/SysDepartmentEditPanel': {

                getComponent: (owner, props) => {
                    return <SysDepartmentEditPanel ref={(inst) => this.sysDepEditFormRef = inst} onSaveSysDep={this.props.onSaveSysDep}/>;
                }
            },
            '/SysDepartmentStaffListPanel': {

                getComponent: (owner, props) => {
                    return <SysDepartmentStaffListPanel ref={(inst) => this.sysDepStaffListRef = inst} />
                }
            },

        };

        const configProps = {
            tabConfigId: 'sysDepartmentEditorTab',
            onTabChange: this.onTabChange,
            tabContentMap: tabPanelContentMap,
        };

        return (
            <UICardTabs {...configProps}>

            </UICardTabs>
        );
    }
}

/**
 * 系统组织部门管理
 */
export default class SysDepartmentListApp extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedDepartment: null,
        };
    }

    onDepartmentSelected = (department) => {
        this.setState({ selectedDepartment: department });
        if(department !== null){
            setTimeout(() => {
                this.sysDepInfoRef.setDepartment(department);
            });
        }
    }

    onSaveSysDep = () => {
        this.sysDepListRef.refreshData();
    }

    render() {
        const { selectedDepartment } = this.state;
        return (
            <PageContent {...this.props} pageInstance={this} >
                <Row gutter={16}>
                    <Col span={10}>
                        <SysDepartmentListPanel ref={(inst) => this.sysDepListRef = inst} onDepartmentSelected={this.onDepartmentSelected} />
                    </Col>

                    <Col span={14}>
                        {
                            selectedDepartment != null ? <SysDepartmentInfoPanel ref={(inst) => this.sysDepInfoRef = inst} onSaveSysDep={this.onSaveSysDep} /> :
                                <Alert message="请选择组织部门,查看部门信息" type="info" showIcon />
                        }
                    </Col>
                </Row>
            </PageContent>
        );
    }
};